package org.vison.wonfu.framework.soa.context;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.apache.hc.core5.http.HttpRequestInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.vison.wonfu.framework.commons.utils.StringUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class SoaApplicationContext {

    private static final Logger logger = LoggerFactory.getLogger(SoaApplicationContext.class);


    private static final Map<String, Object> ATTRIBUTES = new ConcurrentHashMap<>();

    private SoaApplicationContext() {
        //
    }

    public static void start() {
        // start all ext
    }

    public static void destroy() {
        // destroy all ext
    }

    /**
     * get application name (appid)
     *
     */
    public static String getName() {
        return "";
    }

    /**
     * admin server url
     */
    public static String getAdminUrl() {
        return "";
    }

    /**
     * server.servlet.context-path
     */
    public static String getContextPath() {
        return "";
    }

    /**
     * getCustomizeObjectMapper
     * @param appId
     * @return
     */
    public static Object getCustomizeObjectMapper(String appId) {
        if(StringUtils.isEmpty(appId)) {
            return ObjectMapperHolder.objectMapper;
        }
        Object object =  ATTRIBUTES.get(appId);
        if(object == null) {
            ATTRIBUTES.put(appId, ObjectMapperHolder.objectMapper);
            return ObjectMapperHolder.objectMapper;
        }
        return object;
    }

    public static ObjectMapper getDefaultObjectMapper() {
        return ObjectMapperHolder.objectMapper;
    }


    public static HttpRequestInterceptor getHttpRequestInterceptor(){
        // 从 spring context 获取
        return HttpInterceptorHolder.httpRequestInterceptor;
    }


    private static class ObjectMapperHolder {
        private static final ObjectMapper objectMapper;

        static {
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
            mapper.configure(SerializationFeature.INDENT_OUTPUT, false);
//            mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
            mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
            objectMapper = mapper;
        }
    }

    private static class HttpInterceptorHolder {
        private static final HttpRequestInterceptor httpRequestInterceptor;

        static {
            httpRequestInterceptor = (httpRequest, entityDetails, httpContext) -> {
                // 记录请求信息
                logger.info("HttpRequestInterceptor: {}", httpRequest);
            };
        }
    }


}
